package com.icode.web.controller.User;

import com.icode.core.dto.user.UserDTO;
import com.icode.core.shared.MailHandle;
import com.icode.core.shared.ValidateNumHandle;
import com.icode.service.user.MessageService;
import com.icode.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;


/**
 * Created with IntelliJ IDEA.
 * User: sunk
 * Date: 14-12-26
 * Time: 上午11:30
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;

    @RequestMapping(value = "form", method = RequestMethod.GET)
    private ModelAndView showForm() {
        return new ModelAndView("front/user/register", "userDTO", new UserDTO());
    }

    @RequestMapping(value = "verify/{random}", method = RequestMethod.GET)
    @ResponseBody
    public String verify(HttpSession session, @PathVariable String random) {
        return userService.verify(session);
    }

    @RequestMapping(value = "form", method = RequestMethod.POST)
    private String submitForm(@ModelAttribute(value = "userDTO") @Valid UserDTO userDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "front/user/register";
        }
        userService.saveOrUpdate(userDTO);
        messageService.removePhoneNum(userDTO.getUsername());
        return "redirect:/";
    }

    @RequestMapping(value = "sendValidateNum")
    @ResponseBody
    private String sendValidateNum(String userName) {
        String result = messageService.sendValidateNum(userName);
        String str = ValidateNumHandle.checkBalance();
        String[] array = str.split("&");
        String balance = array[1].substring(8);
        if (Integer.parseInt(balance) <= 200) {
            try {
                MailHandle.sendHTMLEmail(balance);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}
